package org.flow.basic.doubts.tjbase.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * @author xl-9527
 * @since 2024/8/30
 */
public class NioFilesendJavaIo implements JavaIo {

    private final static long MAX_SIZE = 1L << 25;

    @Override
    public void readFile(final String filePath, final int size) {
        try (
                final FileInputStream inputStream = new FileInputStream(filePath);
                final FileOutputStream outputStream = new FileOutputStream(filePath + "nio-file-send" + System.currentTimeMillis())
        ) {
            final FileChannel inChannel = inputStream.getChannel();
            final FileChannel outChannel = outputStream.getChannel();

            if (inputStream.available() > MAX_SIZE) {
                long position = 0;
                while (position < inputStream.available()) {
                    final long transferSize = inChannel.transferTo(position, Math.min(MAX_SIZE, inputStream.available() - position), outChannel);
                    position += transferSize;
                }
            } else {
                inChannel.transferTo(0, inputStream.available(), outChannel);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void writeFile(final byte[] bytes, final FileOutputStream fileOutputStream) throws IOException {

    }
}
